package main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"time"
)

func main4() {

	{
		student := Student{ID: 5} //也是条件

		tx := DB.Model(&student).Where("age=?", 19).UpdateColumn("age", gorm.Expr("age+?", 1))
		if tx.Error != nil {
			if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
				fmt.Println("not found")
			} else {
				fmt.Println("error", tx.Error.Error())
			}
		} else {
			fmt.Println("tx.RowsAffected:", tx.RowsAffected)
			fmt.Println(student)
		}
	}
	fmt.Println("-----------------------")
	{
		student := Student{ID: 5} //ID

		tx := DB.Model(&student).UpdateColumn("age", gorm.Expr("age+?", 1))
		if tx.Error != nil {
			if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
				fmt.Println("not found")
			} else {
				fmt.Println("error", tx.Error.Error())
			}
		} else {
			fmt.Println("tx.RowsAffected:", tx.RowsAffected)
			fmt.Println(student)
		}
	}
	fmt.Println("-----------------------")
	{
		student := Student{Age: 25} // NOT ID

		tx := DB.Model(&student).UpdateColumn("age", gorm.Expr("age+?", 1))
		if tx.Error != nil {
			if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
				fmt.Println("not found")
			} else {
				fmt.Println("error", tx.Error.Error())
			}
		} else {
			fmt.Println("tx.RowsAffected:", tx.RowsAffected)
			fmt.Println(student)
		}
	}
	fmt.Println("-----------------------")
	{
		ts, _ := time.Parse("2006-01-02 15:04:05", `2024-10-11 00:22:13`)

		student := Student{Birthday: ts} // NOT ID
		//Model: if user's primary key is non-blank, will use it as condition
		tx := DB.Model(&student).UpdateColumn("age", gorm.Expr("age+?", 1))
		if tx.Error != nil {
			if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
				fmt.Println("not found")
			} else {
				fmt.Println("error", tx.Error.Error())
			}
		} else {
			fmt.Println("tx.RowsAffected:", tx.RowsAffected)
			fmt.Println(student)
		}
	}
}
